import { Color3, Engine, HemisphericLight, Vector3, Sprite, Scene, ArcRotateCamera, PointLight, StandardMaterial, Texture, ShaderMaterial, IAnimationKey, AssetsManager, MeshAssetTask, AbstractMesh, PickingInfo, Mesh } from 'babylonjs'
import 'babylonjs-loaders';


// 点击交互
export class Demo7 {
  private dom: HTMLCanvasElement
  private engine: Engine
  private scene: Scene
  private camera: ArcRotateCamera
  private switch: Boolean
  private material: any

  constructor(dom: HTMLCanvasElement) {
    this.dom = dom
    this.engine = new Engine(this.dom, true)  // 设置引擎
    this.scene = new Scene(this.engine)   // 创建场景
    this.camera = new ArcRotateCamera("Camera", 0,0,0, Vector3.Zero(), this.scene); // 创建相机
    this.camera.attachControl(this.dom, false)  // 把相机放到画布
    this.scene.ambientColor = new Color3(1, 1, 1);
    this.switch = false


    //半球光源
    const light = new HemisphericLight('light', new Vector3(1, 1, 0), this.scene);
    const that = this;

    const box1 = Mesh.CreateSphere('box1', 20, 20, this.scene)
    const m = new StandardMaterial('1', this.scene)
    m.ambientColor = new Color3(1, 0, 1)
    box1.material = m
    const box2 = Mesh.CreateBox('box2', 20, this.scene)
    box1.position.set(0, 20, 0)

    this.scene.onPointerDown = function (evt) {
      const pickResult = that.scene.pick(this.pointerX, this.pointerY);

      if (pickResult?.hit) {


        if (that.switch) {
          const mt = new StandardMaterial('m1', that.scene);
          mt.emissiveColor = new Color3(1, 1, 1)
          pickResult.pickedMesh!.material = that.material
        } else {
          that.material = pickResult.pickedMesh!.material
          console.log(that.material);

          const mt = new StandardMaterial('m1', that.scene);
          mt.emissiveColor = new Color3(255, 255, 0)
          pickResult.pickedMesh!.material = mt
        }
        that.switch = !that.switch

      }
    };


    window.addEventListener('resize', () => {
      this.engine.resize();
    })
  }
  render() {
    // 引擎渲染场景
    this.engine.runRenderLoop(() => {
      this.scene.render()
    })
  }
}


